package com.mxpio.erp.quality.service.impl;

import com.googlecode.aviator.AviatorEvaluator;
import com.googlecode.aviator.Options;
import com.mxpio.erp.common.quality.entity.InspectionBill;
import com.mxpio.erp.common.quality.entity.InspectionBillCheckDetail;
import com.mxpio.erp.common.quality.service.InspectionBillCheckDetailService;
import com.mxpioframework.common.vo.Result;
import com.mxpioframework.jpa.JpaUtil;
import com.mxpioframework.system.service.impl.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;


@Service
public class InspectionBillCheckDetailServiceImpl extends BaseServiceImpl<InspectionBillCheckDetail> implements InspectionBillCheckDetailService {
    @Override
    @Transactional
    public int deleteByBizNo(String bizNo) {
        return JpaUtil.lind(InspectionBillCheckDetail.class).equal("bizNo", bizNo).delete();
    }

    @Override
    @Transactional
    public Result<Object> checkDetails(InspectionBill bill, List<InspectionBillCheckDetail> details) {
        if (details==null||details.size()==0){
            return Result.error("提交数据为空");
        }
        for (InspectionBillCheckDetail d:details){
            if (StringUtils.isBlank(d.getMeasurement())){
                return Result.error("提交数据存在实测值为空的情况，请检查");
            }
        }
        Map<String, List<InspectionBillCheckDetail>> collect = details.stream().collect(Collectors.groupingBy(InspectionBillCheckDetail::getInspectionItemType));//按检验类型分组
        if (collect.containsKey("1")){//定量
            List<InspectionBillCheckDetail> details1 = collect.get("1");
            for (InspectionBillCheckDetail detail:details1){
                String comparator = detail.getComparator();
                String expStr = "";
                if ("[]".equals(comparator)){//区间值
                    expStr = "val>="+detail.getMinValue()+" && "+"val<="+detail.getMaxValue();
                }else if ("=".equals(comparator)){
                    expStr = "val=="+detail.getTargetValue();
                }else if ("≠".equals(comparator)){
                    expStr = "val!="+detail.getTargetValue();
                }else{
                    expStr = "val"+comparator+detail.getTargetValue();
                }
                Map<String,Object> valueMap = new HashMap<>();
                valueMap.put("val",new BigDecimal(detail.getMeasurement()));//数字需要转换成对象，不然解析成字符串就没法运算了
                AviatorEvaluator.setOption(Options.ALWAYS_PARSE_FLOATING_POINT_NUMBER_INTO_DECIMAL, true);//精确计算
                Boolean result = (Boolean) AviatorEvaluator.execute(expStr,valueMap);
                detail.setTestResult(result?"1":"0");
            }
        }
        if (collect.containsKey("2")){//定性
            List<InspectionBillCheckDetail> details2 = collect.get("2");
            for (InspectionBillCheckDetail detail:details2){
                String comparator = detail.getComparator();
                String expStr = "";
                Map<String,Object> valueMap = new HashMap<>();
                if ("=".equals(comparator)){
                    expStr = "val=='"+detail.getTargetValue()+"'";
                }else if ("≠".equals(comparator)){
                    expStr = "val!='"+detail.getTargetValue()+"'";
                }else if ("include".equals(comparator)){
                    List<String> targetList = Stream.of(detail.getTargetValue().split(",")).collect(Collectors.toList());
                    valueMap.put("list",targetList);
                    expStr = "include(list,val)";
                }else{
                    return Result.error("定性时，比较符只能为=、≠或者include（包含）");
                }
                valueMap.put("val",detail.getMeasurement());//数字需要转换成对象，不然解析成字符串就没法运算了
                Boolean result = (Boolean) AviatorEvaluator.execute(expStr,valueMap);
                detail.setTestResult(result?"1":"0");
            }
        }
        JpaUtil.update(details);
        /*boolean updateFlag = false;  //单据状态变更放在生成样本；开始、结束时间手动填写
        if (bill.getInspectionStartTime()==null){
            updateFlag = true;
            bill.setInspectionStartTime(new Date());
            bill.setCheckStatus(InspectionEnums.CheckStatus.CHECKING.getCode());
            //JpaUtil.update(bill);
        }
        List<InspectionBillCheckDetail> uncheckList = JpaUtil.linq(InspectionBillCheckDetail.class).equal("bizNo", bill.getBizNo()).isNull("testResult").list();
        if (CollectionUtils.isEmpty(uncheckList)){
            updateFlag = true;
            bill.setInspectionFinishTime(new Date());//更新检验完成时间
            //JpaUtil.update(bill);
        }
        if (updateFlag){
            JpaUtil.update(bill);
        }*/
        return Result.OK("检验完成",details);
    }

/*    public static void main(String[] args) {
        Map<String,Object> valueMap = new HashMap<>();
        valueMap.put("val","test1");
        List<String> collect = Stream.of("test,add,sum".split(",")).collect(Collectors.toList());
        valueMap.put("list",collect);//数字需要转换成对象，不然解析成字符串就没法运算了
        valueMap.put("val","test1");
        String expStr = "include(list,val)";
        Boolean result = (Boolean) AviatorEvaluator.execute(expStr,valueMap);
        System.out.println(result);
    }*/
}
